package com.sufen.seckill.controller;

import com.sufen.seckill.pojo.User;
import com.sufen.seckill.service.IGoodsService;
import com.sufen.seckill.vo.DetailVo;
import com.sufen.seckill.vo.GoodsVo;
import com.sufen.seckill.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author sufen
 * @Date 2021/10/19 15:36
 * @Version 1.0
 * 功能描述：跳转登录页到商品列表页面
 */

@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodsController {

//    @Autowired
//    private IUserService userService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 页面缓存到redis里了，用String的形式，过期时间60秒。
     * 用的是手动渲染thymeleaf的方式，才能得到这个传完参的thymeleaf界面，才能把它以String的形式传到redis里面。
     * @param model
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response){
//        if(StringUtils.isEmpty(ticket)){
//            log.info("没携带cookie，转到login页");
//            return "login";
//        }
//        User user=userService.getUserByCookie(ticket,request,response);
////        User user= (User) session.getAttribute(ticket);
//        if(user==null){
//            log.info("携带的cookie从数据库中取不到user，转到login页");
//            return "login";
//        }
//        log.info("ok,转到goodsList页");
//        log.info("toList这个controller获取的参数user成功被WebConfig里的前置参数校验器校验，成功");
        ValueOperations valueOperations=redisTemplate.opsForValue();
        String html=(String) valueOperations.get("goodsList");
        //如果不为空，则代表已渲染过的页面已经存到了redis里面。直接返回就好了
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        //如果不为空，手动渲染，存进redis里面。并返回
        WebContext webContext=new WebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap());
        html=thymeleafViewResolver.getTemplateEngine().process("goodsList",webContext);
        if(!StringUtils.isEmpty(html)){
            valueOperations.set("goodsList",html,60, TimeUnit.SECONDS);
        }

        return html;
//        return "goodsList";
    }

    @RequestMapping(value="/toDetail2/{goodsId}",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail2(Model model, User user, @PathVariable Long goodsId,HttpServletRequest request,HttpServletResponse response){
        ValueOperations valueOperations=redisTemplate.opsForValue();
        String html=(String) valueOperations.get("goodsDetails:"+goodsId);
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user",user);
        GoodsVo goodsVo=goodsService.findGoodsVoByGoodsId(goodsId);
        Date startDate=goodsVo.getStartDate();
        Date endDate=goodsVo.getEndDate();
        Date nowDate=new Date();
        //秒杀状态
        int secKillStatus=0;
        //秒杀倒计时
        int remainSeconds=0;
        //秒杀还未开始
        if(nowDate.before(startDate)){
            remainSeconds=((int)(startDate.getTime()-nowDate.getTime())/1000);
        }else if(nowDate.after(endDate)){
            //秒杀已结束
            secKillStatus=2;
            remainSeconds=-1;
        }else{
            //秒杀中
            secKillStatus=1;
            remainSeconds=0;
        }
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("goods",goodsVo);
        WebContext webContext=new WebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap());
        html=thymeleafViewResolver.getTemplateEngine().process("goodsDetail",webContext);
        if(!StringUtils.isEmpty(html)){
            valueOperations.set("goodsDetail:"+goodsId,html,60,TimeUnit.SECONDS);
        }
        return html;
//        return "goodsDetail";
    }

    /**
     * 做动静分离，静态直接传，动态用ajax请求动态数据
     * 10月24日，39，商品详情页面静态化，为的是动静分离，不能用model传thymeleaf这种页面了。
     * 要传静态htm给浏览器缓存，动态的就用ajax去请求。实现步骤：在GoodsController里面复制
     * 商品详情页的controller代码，然后把model给前端传参的语句全注释了，
     * 然后把model传参的所有参数写一个Vo，叫DetailVo，用于给ajax返回请求的结果实体对象，
     * 其实这个DetailVo里面的参数和之前model传给thymeleaf的是一摸一样的。
     * @param
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value="/detail/{goodsId}")
    @ResponseBody
    public RespBean toDetail( User user, @PathVariable Long goodsId){
//        model.addAttribute("user",user);
        GoodsVo goodsVo=goodsService.findGoodsVoByGoodsId(goodsId);
        Date startDate=goodsVo.getStartDate();
        Date endDate=goodsVo.getEndDate();
        Date nowDate=new Date();
        //秒杀状态
        int secKillStatus=0;
        //秒杀倒计时
        int remainSeconds=0;
        //秒杀还未开始
        if(nowDate.before(startDate)){
            remainSeconds=((int)(startDate.getTime()-nowDate.getTime())/1000);
        }else if(nowDate.after(endDate)){
            //秒杀已结束
            secKillStatus=2;
            remainSeconds=-1;
        }else{
            //秒杀中
            secKillStatus=1;
            remainSeconds=0;
        }
//        model.addAttribute("secKillStatus", secKillStatus);
//        model.addAttribute("remainSeconds",remainSeconds);
//        model.addAttribute("goods",goodsVo);
        DetailVo detailVo=new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(goodsVo);
        detailVo.setSecKillStatus(secKillStatus);
        detailVo.setRemainSeconds(remainSeconds);
        return RespBean.success(detailVo);

//        return "goodsDetail";
    }
}
